package cn.tedu.ivos.audit.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.audit.mapper.AuditMapper;
import cn.tedu.ivos.audit.pojo.dto.AuditQuery;
import cn.tedu.ivos.audit.pojo.dto.AuditSaveParam;
import cn.tedu.ivos.audit.pojo.entity.Audit;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.base.enums.AuditStatusEnum;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Transactional
@Service
public class AuditServiceImpl implements AuditService {
    @Autowired
    AuditMapper auditMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ApplicationMapper applicationMapper;
    @Override
    public void insertAudit(Application application) {
        log.debug("为当前申请单新增审批单业务，参数={}",application);
        List<Long> userIdList = application.getAuditUserIdList();
        for (int i = 0;i<userIdList.size();i++){
            Audit audit = new Audit();
            //设置  申请单id
            audit.setApplicationId(application.getId());
            //设置  审批人id
            audit.setAuditUserId(userIdList.get(i));
            //设置  审批排序
            audit.setAuditSort(i);
            //设置  审批状态
            if (i==0){
                audit.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
            }else {
                audit.setAuditStatus(AuditStatusEnum.PENDING.getCode());
            }
            audit.setCreateTime(new Date());
            auditMapper.insertAudit(audit);
        }
    }

    @Override
    public List<AuditVO> selectAuditByApplicationId(Long applicationId) {
        log.debug("根据申请单id查审批单业务，参数：{}",applicationId);
        List<AuditVO> auditVOList = auditMapper.selectByApplicationId(applicationId);
        return auditVOList;
    }

    @Override
    public List<AuditVO> selectAudit(AuditQuery auditQuery) {
        log.debug("查询审批单业务，参数：{}",auditQuery);
        List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
        for (int i = 0;i < auditVOList.size();i++){
            AuditVO auditVO = auditVOList.get(i);
            //前端显示页面需要显示该申请单的所有审批人数据，定义一个方法专门处理需要添加的瞬态属性数据
            assignAuditUserList(auditVO);
        }
        return auditVOList;
    }

    @Override
    public void updateAudit(AuditSaveParam auditSaveParam) {
        log.debug("更新申请单审批单状态业务，参数={}",auditSaveParam);
        Audit audit = new Audit();
        BeanUtils.copyProperties(auditSaveParam,audit);
        audit.setUpdateTime(new Date());
        Application application = new Application();
        application.setId(audit.getApplicationId());
        application.setUpdateTime(new Date());
        if (audit.getAuditStatus().equals(AuditStatusEnum.AUDITED.getCode())){//审批通过
            //更新当前审批单
            auditMapper.update(audit);
            //判断是第几位审批
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            Integer count = auditMapper.selectRestAuditCount(auditQuery);
            if (count>0){//后续还有人需要审核
                //下一条审批数据是当前审批数据的次序+1
                auditQuery.setAuditSort(audit.getAuditSort()+1);
                //根据申请单id和审批次序查出当前审批单之后的下一条审批单
                List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
                if (auditVOList != null && auditVOList.size()>0){
                    AuditVO auditVO = auditVOList.get(0);
                    Audit audit2 = new Audit();
                    audit2.setId(auditVO.getId());
                    audit2.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
                    auditMapper.update(audit2);
                }
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.update(application);
            }else {
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.update(application);
            }
        }else {//驳回操作
            auditMapper.update(audit);
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(auditSaveParam.getRejectReason());
            applicationMapper.update(application);

            //处理其余的审批单（方案1）
//            auditMapper.deleteRestAudit(audit.getApplicationId());
            //处理其余的审批单（方案2）
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
            if (auditVOList != null && auditVOList.size()>0){
                for (int i=0;i<auditVOList.size();i++){
                    AuditVO auditVO = auditVOList.get(i);
                    if (AuditStatusEnum.PENDING.getCode().equals(auditVO.getAuditStatus())){
                        auditMapper.deleteById(auditVO.getId());
                    }
                }
            }
        }
    }

    private void assignAuditUserList(AuditVO auditVO){
        List<Long> auditUserIdList = new ArrayList<>();
        List<String> auditUsernameList = new ArrayList<>();
        List<AuditVO> list = selectAuditByApplicationId(auditVO.getApplicationId());
        for (int i = 0;i<list.size();i++){
            AuditVO auditVO1 = list.get(i);
            auditUserIdList.add(auditVO1.getAuditUserId());
            UserVO userVO = userMapper.selectById(auditVO1.getAuditUserId());
            auditUsernameList.add(userVO.getUsername());
        }
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String username:auditUsernameList){
            stringJoiner.add(username);
        }
        auditVO.setAuditUserIdList(auditUserIdList);
        auditVO.setAuditUsernameList(stringJoiner.toString());
    }
}
